package com.neucollege.system.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.*;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;

@Component
@Data
public class KeyUtils {
    private String keypairPath = "keypair";

    public JWTSigner getPrivateSigner() throws IOException, NoSuchAlgorithmException, ClassNotFoundException {
        return JWTSignerUtil.rs512(getKeyPair().getPrivate());
    }
    public JWTSigner getPublicSigner() throws IOException, NoSuchAlgorithmException, ClassNotFoundException {
        return JWTSignerUtil.rs512(getKeyPair().getPublic());
    }

    private boolean isKeyExist() throws NoSuchAlgorithmException {
        //TODO:检测密钥是否被篡改
        //检测路径下是否有对应文件
        File publicKeyFile = new File(keypairPath);
        return publicKeyFile.exists();
    }

    private void generateKey() throws IOException {
        KeyPair keyPair = SecureUtil.generateKeyPair(SignAlgorithm.SHA512withRSA.getValue());
        ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(keypairPath));
        ops.writeObject(keyPair);
        ops.close();
    }

    public KeyPair getKeyPair() throws IOException, ClassNotFoundException, NoSuchAlgorithmException {
        if(!isKeyExist()){
            generateKey();
        }
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(keypairPath));
        return (KeyPair) ois.readObject();
    }
}




















